# -*- coding: utf-8 -*-
# @File     : api.py
# @Author   : bingjia
# @Time     : 2020/8/6 18:51
# @Desc     : 信息api视图
from django.apps import apps
from django.shortcuts import get_list_or_404, get_object_or_404

from operation.base.api import viewsets
from operation.base.api import response
from operation.base.api import exceptions as exc
from operation.base.utils.parse_data import parse_data

from . import models
from . import services
from . import validators
from . import permissions
from . import serializers


class InfoViewSet(viewsets.ModelViewSet):
    """
    信息视图
    """
    queryset = models.Info
    "验证"
    validator_class = validators.InfoValidator
    "序列化"
    serializer_class = serializers.InfoSerializer
    "权限"
    permission_classes = (permissions.InfoPermission,)

    def list(self, request, *args, **kwargs):
        """
        群查（项目信息情况）
        """
        resource_id = kwargs.get("resource_id", None)
        project_model = apps.get_model("projects", "Project")
        project_object = get_object_or_404(project_model.objects.all(), pk=resource_id)

        self.check_permissions(request, 'list', project_object)

        info_object_list = get_list_or_404(self.queryset, project=project_object)
        if info_object_list:
            page = self.paginate_queryset(info_object_list)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            else:
                serializer = self.get_serializer(info_object_list, many=True)

            return response.Ok(serializer.data)
        else:
            return response.Ok({"message": "project no info"})

    def retrieve(self, request, *args, **kwargs):
        """
        单查（项目信息情况）
        """
        pass

    def create(self, request, *args, **kwargs):
        """
        创建
        """
        resource_id = kwargs.get("resource_id", None)
        project_model = apps.get_model("projects", "Project")
        project_object = get_object_or_404(project_model.objects.all(), pk=resource_id)

        self.check_permissions(request, 'create', project_object)
        "验证数据"
        try:
            data = parse_data(request.data, cls=validators.InfoValidator)
            info = self.queryset(
                title=data["title"],
                type=data["type"],
                content=data["content"],
                user=request.user,
                send=project_object,
                attachment=request.data.get("attachment", None)
            )
            info.save()
        except exc.ParseError as e:
            raise exc.BadRequest(e.detail)

        serializer = self.get_serializer(info)
        return response.Created(serializer.data)


def destroy(self, request, *args, **kwargs):
    """
    删除
    """
    raise exc.MethodNotAllowed(method='DELETE')


def update(self, request, *args, **kwargs):
    """
    修改
    """
    raise exc.MethodNotAllowed(method='PUT')


class InfoAdminViewSet(viewsets.ModelViewSet):
    """
    信息管理视图
    """

    def create(self, request, *args, **kwargs):
        """
        创建
        """
        self.check_permissions(request, 'create', None)
        "验证数据"
        try:
            data = parse_data(request.data, cls=validators.InfoValidator)
            info = self.queryset(
                title=data["title"],
                type=data["type"],
                content=data["content"],
                user=request.user,
                attachment=request.data.get("attachment", None)
            )
            info.save()
        except exc.ParseError as e:
            raise exc.BadRequest(e.detail)

        serializer = self.get_serializer(info)
        return response.Created(serializer.data)

    def destroy(self, request, *args, **kwargs):
        """
        删除
        """

    def partial_update(self, request, *args, **kwargs):
        """
        修改
        """

    def list(self, request, *args, **kwargs):
        """
        群查（项目信息情况）
        """
        self.check_permissions(request, 'list', None)

        info_object_list = get_list_or_404(self.queryset)
        if info_object_list:
            page = self.paginate_queryset(info_object_list)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            else:
                serializer = self.get_serializer(info_object_list, many=True)

            return response.Ok(serializer.data)
        else:
            return response.Ok({"message": "project no info"})

    def retrieve(self, request, *args, **kwargs):
        """
        单查（项目信息情况）
        """
        pass
